<!-- 开发部：物料计划安排 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">计划明细</h1>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          @currentRow="currentRow"
          :getTableList="getTableList"
          @confirmChange="confirmChange"
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>

    <!-- 打勾指令材料复制到指令 -->
    <el-drawer v-model="dialogTableVisible2" :direction="'ttb'" size="small" :with-header="false">
      <Find :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
      <el-card shadow="never" :body-style="{ padding: '11px 20px' }">
        <div slot="header" class="f16">
          <span style="font-weight: 600">选择订单</span>
        </div>
        <Table :tableHeader="tableHeader2" :tableData="tableData2" class="mr55" selection @selectList="selectTable2List" />
        <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
      </el-card>
    </el-drawer>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
import LoginWork from '@/utils/LoginWork'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'MaterialPlan'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref } from 'vue'
const dialogTableVisible2 = ref(false)

const formList = ref<any>([
  {
    type: 'input',
    inputPlaceholder: '请输入指令号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectLabel: '客人类型',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入货号',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '物料配套完成日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '选择指令'
  },
  {
    type: 'button',
    checkboxLabel: '导出计划'
  },
  {
    type: 'button',
    checkboxLabel: '移出指令'
  },
  {
    type: 'button',
    checkboxLabel: '导入计划'
  }
])
const formList2 = ref<any>([
  {
    type: 'input',
    inputPlaceholder: '请输入指令号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectLabel: '客人类型',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入货号',
    inputValue: ''
  },
  {
    type: 'dateSingle',
    dateLabel: '物料配套完成日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '选择'
  },
  {
    type: 'button',
    checkboxLabel: '返回'
  }
])
const imgList = ref([])
const tableHeader = ref([
  {
    change: true,
    label: '指令号',
    prop: 'lotNo'
  },
  {
    change: true,
    label: '客人类型',
    prop: 'custStyle'
  },
  {
    change: true,
    label: '备料员',
    prop: 'mtlPerson'
  },
  {
    change: true,
    label: '工厂货号',
    prop: 'style'
  },
  {
    change: true,
    label: '颜色',
    prop: 'color'
  },
  {
    change: true,
    label: '数量',
    prop: 'qty'
  },
  {
    change: true,
    label: '客户交期',
    prop: 'deliveryDate'
  },
  {
    type: 'dateSingle',
    label: '物料配套完成日期',
    prop: 'completeDate'
  },
  {
    type: 'img',
    label: '图片',
    fixed: true,
    prop: 'photoPath',
    srcList: imgList
  }
])

// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '导入计划') {
    upload()
  }
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '选择指令') {
    dialogTableVisible2.value = true
  }
  if (content === '移出指令') {
    const res = await LoginWork.post<any, any>('/prod/plan/removePcOrderPlan?choose=1', currentTable1Row.value)
    if (res.code === 200) {
      JMessage.success('移除成功')
      getTableList()
    } else {
      JMessage.warning(res.message)
    }
  }
  if (content === '导出计划') {
    const res = await fileRequest.post<any, any>('/prod/plan/downloadExcelPlan', {
      choose: 1,
      custStyle: formList.value.find(
        (item: any) => item.selectLabel && Jzhcn.Find[item.selectLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '客人类型'
      ).selectValue,
      endDate: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '物料配套完成日期'
      )?.dateValue?.[1],
      lotNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
      ).inputValue,
      startDate: formList.value.find(
        (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '物料配套完成日期'
      )?.dateValue?.[0],
      style: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
      ).inputValue
    })
    console.log(res)
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    link.download = `物料计划安排.xls` //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}

const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/prod/plan/arrangePlanList', {
    choose: 1,
    custStyle: formList.value.find(
      (item: any) => item.selectLabel && Jzhcn.Find[item.selectLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '客人类型'
    ).selectValue,
    endDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '物料配套完成日期'
    )?.dateValue?.[1],
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
    )?.inputValue,
    startDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '物料配套完成日期'
    )?.dateValue?.[0],
    style: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  imgList.value = tableDataList.list.map((item: any) => {
    return item.photoPath
  })
  tableData.value = tableDataList.list.map((item: any) => {
    item.deliveryDate === null ? (item.deliveryDate = '') : (item.deliveryDate = item.deliveryDate.split(' ')[0])
    item.completeDate === null ? (item.completeDate = '') : (item.completeDate = item.completeDate.split(' ')[0])
    item.change = 'Y'
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 码制下拉框数据
const getSelectList = async () => {
  const res = await service.get<any, any>('/back/order/allOrderCondition')
  if (res) {
    res.brands.forEach((item: any, index: any) => {
      if (item === null) return
      formList.value
        .find((item: any) => item.selectLabel === '客人类型')
        ?.selectOptions.push({
          optionKey: index,
          optionValue: item,
          optionLabel: item
        })
      formList2.value
        .find((item: any) => item.selectLabel === '客人类型')
        ?.selectOptions.push({
          optionKey: index,
          optionValue: item,
          optionLabel: item
        })
    })
  }
}
onMounted(() => {
  getSelectList()
})
const currentTable1Row = ref({})
const currentRow = (row: any = tableData.value[0]) => {
  currentTable1Row.value = row
}
// 修改后点击确定按钮
const confirmChange = async (row: any) => {
  const res = await LoginWork.post<any, any>('/prod/plan/updatePcOrderPlan?choose=1', row)
  if (res.code === 200) {
    JMessage.success('修改成功')
    getTableList()
  } else {
    JMessage.warning(res.message)
  }
}

// 表二模块
// 表二按钮
const tableHeader2 = ref([
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '客人类型',
    prop: 'custStyle'
  },
  {
    label: '备料员',
    prop: 'mtlPerson'
  },
  {
    label: '鞋名',
    prop: 'style'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    label: '数量',
    prop: 'qty'
  },
  {
    label: '客户交期',
    prop: 'deliveryDate'
  },
  {
    label: '物料配套完成日期',
    prop: 'completeDate'
  }
])
const findClicked2 = async (content: string) => {
  if (content === '置空') {
    formList2.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '选择') {
    if (selectTable2Lists.value.length === 0) {
      JMessage.warning('请勾选订单')
      return
    }
    const res = await LoginWork.post<any, any>(
      '/prod/plan/chooseProdStatusIn?choose=1',
      selectTable2Lists.value.map((item: any) => {
        return item.lotNo
      })
    )
    if (res.code === 200) {
      JMessage.success('选择成功')
      getTableList()
      getTableList2()
      dialogTableVisible2.value = false
    } else {
      JMessage.warning(res.message)
    }
  }
  if (content === '返回') {
    dialogTableVisible2.value = false
  }
}
const tableData2 = ref([])
const isLoading2 = ref(true)
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
// 获取表数据
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = await service.post<any, any>('/prod/plan/choosePlanList', {
    choose: 1,
    custStyle: formList2.value.find(
      (item: any) => item.selectLabel && Jzhcn.Find[item.selectLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '客人类型'
    ).selectValue,
    lotNo: formList2.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
    )?.inputValue,
    startDate: formList2.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '物料配套完成日期'
    )?.dateValue,
    style: formList2.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading2.value = false
  tableData2.value = tableDataList.list
  total2.value = tableDataList.total
}, 500)
onMounted(() => {
  getTableList2()
})
watch(formList2.value, () => {
  getTableList2()
})
const selectTable2Lists = ref([])
const selectTable2List = (selectedList: any) => {
  selectTable2Lists.value = selectedList
}

const upload = async () => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input')
  const maxFileSizeMb = 2
  const maxFilesSizeBytes = maxFileSizeMb * 1024 * 1024
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.addEventListener('change', async function () {
    const files = inputFile.files as any // 获取文件数组
    const file = files[0] // 获取第一个文件对象
    const fileExtension = file.name.split('.').pop()
    if (!fileType.includes(fileExtension as any)) {
      JMessage.warning('上传的文件格式只能是 xls, xlsx')
      document.body.removeChild(inputFile)
      return false
    }
    if (file.size > maxFilesSizeBytes) {
      JMessage.warning('文件大小不能超过2MB!!!')
      document.body.removeChild(inputFile)
      return
    }
    const formData = new FormData() as any
    formData.append('file', file) // 添加文件对象及文件名
    let result = {} as any
    result = (await LoginWork.post('/prod/uploadPcOrderShoePlan', formData)) as any
    if (result.code === 200) {
      JMessage.success(result.message)
      getTableList()
    } else {
      JMessage.error(result.message)
    }
  })
  inputFile.click()
}
</script>

<style lang="less" scoped>
table {
  table-layout: auto !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>
